import { getTenantOptions } from '@/pages/Tenant/Tenant/service';
import { ProCard } from '@ant-design/pro-components';
import { ProFormDigit, ProFormInstance, ProFormList, ProFormSelect, ProFormTextArea, ProFormTimePicker, } from '@ant-design/pro-form';
import { ProForm } from '@ant-design/pro-form/lib/layouts';
import { FooterToolbar } from '@ant-design/pro-layout';
import { Button, Col, Collapse, message, Row, Spin } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
import styles from '../index.less';
import { getChargeDetail, updateChargeItem } from '../service';
import type { updateForm, updateItem } from '../types';
import { decodeTimeItem, encodeTimeItem, getTimeMin, MinToDate } from './utils';

const { Panel } = Collapse;

interface addProps {
  close: () => void;
  id?: string;
}

export default (prop: addProps) => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const tenantId = currUser?.tenantId;

  const form = useRef<ProFormInstance>();
  const { close, id } = prop;
  const [spinVisible, setSpinVisible] = useState(false);

  const [updataItem, setUpdataItem] = useState<updateItem>();

  useEffect(() => {
    if (!id) return;
    setSpinVisible(true);
    getChargeDetail(id).then((res) => {
      if (res && res.data) {
        setUpdataItem(res.data);
        const data = res.data;

        const values = {
          ...data,
          ...data?.rules[0],
          effectTime: [
            MinToDate(res.data?.rules[0]?.effectStartTime || 0).format('HH"mm'),
            MinToDate(res.data?.rules![0]?.effectEndTime || 0).format('HH"mm'),
          ],
          timeItems: data?.rules[0]?.timeItems.map(decodeTimeItem),
          maxPrice: data?.rules[0]?.maxPrice ? data?.rules[0]?.maxPrice / 100 : '',
          tenant: { value: data?.tenantId, label: data?.tenantName },
        };
        form.current?.setFieldsValue(values);
        setSpinVisible(false);
      }
    });
  }, []);

  return (
    <Spin spinning={spinVisible}>
      <ProForm<updateForm>
        formRef={form}
        submitter={{
          // 完全自定义整个区域
          render: (props, doms) => {
            return [
              <FooterToolbar key="addFooterBar">
                <Button key="rest" onClick={() => props.form?.resetFields()}>
                  重置
                </Button>
                ,
                <Button type="primary" key="submit" onClick={() => props.form?.submit?.()}>
                  提交
                </Button>
              </FooterToolbar>,
            ];
          },
        }}
        onFinish={async (values) => {
          const value: any = {
            schemeId: id,
            comment: values.comment,
            name: values.name,
            tenantId: values.tenant || tenantId,
            rules: [
              {
                maxPrice: (values?.maxPrice ?? 0) * 100,
                effectStartTime:
                    values?.effectTime && getTimeMin(values?.effectTime[0].split(' ')[1]),
                effectEndTime: values?.effectTime && getTimeMin(values.effectTime[1].split(' ')[1]),
                timeItems: values?.timeItems?.map(encodeTimeItem),
                freeTime: values?.freeTime,
                type: 'small',
              },
            ],
          };
          const res = await updateChargeItem(value);
          if (res) {
            if (res.code == 0) {
              message.success('更新成功');
              close();
              return true;
            }
            message.error('更新失败' + res?.message);
            return false;
          }
          return false;
        }}
        title="更新收费"
      >
        <ProCard
          title={<div style={{ fontSize: 20, fontWeight: 700 }}>基本信息</div>}
          className={styles.card}
          style={{ borderBottomLeftRadius: 0, borderBottomRightRadius: 0 }}
          bordered={false}
        >
          <Row gutter={16}>
            <Col lg={8} md={12} sm={24}>
              <ProFormDigit
                label={'规则名称'}
                name="name"
                rules={[{ required: true, message: '请输入规则名称' }]}
                placeholder="自定义规则名称"
              />
            </Col>
            {tenantId == '1' && (
              <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                <ProFormSelect
                  label={'所属企业'}
                  name="tenant"
                  showSearch
                  params={{ page: 1, pageSize: 10 }}
                  rules={[{ required: true, message: '请选择所属企业' }]}
                  request={async (params, props) => {
                    const res: any = await getTenantOptions({
                      ...params,
                      name: props.text,
                    });
                    if (res)
                      return res.data.map((item: { id: any; name: any }, index: any) => {
                        return {
                          value: item.id,
                          label: item.name,
                        };
                      });
                  }}
                  placeholder="选择所属企业（如未找到目标企业，请先创建企业）"
                />
              </Col>
            )}
          </Row>
          <Row gutter={16}>
            <Col lg={{ span: 18 }} md={{ span: 24 }} sm={24}>
              <ProFormTextArea
                label={'规则描述'}
                name="comment"
                rules={[{ required: true, message: '请输入规则描述' }]}
                placeholder="输入规则描述"
              />
            </Col>
          </Row>
        </ProCard>
        <ProCard
          style={{ borderTopLeftRadius: 0, borderTopRightRadius: 0 }}
          title={<div style={{ fontSize: 20, fontWeight: 700 }}>通道配置</div>}
          bordered={false}
        >
          <Collapse collapsible="header" defaultActiveKey={['0']} /*  onChange={onChange} */>
            <Panel header={`小型车配置`} key={'0'}>
              <Row gutter={16}>
                <Col lg={8} md={12} sm={24}>
                  <ProFormTimePicker.RangePicker
                    fieldProps={{
                      format: 'HH:mm',
                    }}
                    placeholder={['请选择时间', '请选择时间']}
                    label={'收费时段'}
                    name="effectTime"
                    rules={[{ required: true, message: '请输入规则名称' }]}
                  />
                </Col>
                <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                  <ProFormDigit
                      label={ '免费时长' }
                      name="freeTime"
                      placeholder="停车免费时长（单位：分钟）"
                      fieldProps={ { addonAfter: '分钟', precision: 2 } }
                      rules={ [ { required: true, message: '请选择免费时长' } ] }
                  />
                </Col>
              </Row>
              <Row gutter={16}>
                <Col lg={8} md={12} sm={24}>
                  <ProFormDigit
                      label={ '单日最高限额' }
                      name="maxPrice"
                      placeholder="单日最高的收费限额（单位：元）"
                      fieldProps={ { addonAfter: '￥', precision: 2 } }
                      rules={ [ { required: true, message: '请输入单日最高限额' } ] }
                  />
                </Col>
              </Row>
              <ProFormList
                name="timeItems"
                label={<div style={{ fontSize: 16, fontWeight: 700 }}>用户信息</div>}
                initialValue={[{}]}
                copyIconProps={{
                  tooltipText: '复制此行到末尾',
                }}
                deleteIconProps={{
                  tooltipText: '不需要这行了',
                }}
              >
                {(meta, index, action, count) => (
                  <Row gutter={16}>
                    <Col span={1}>
                      <ProForm.Item label="#">{index + 1}</ProForm.Item>
                    </Col>
                    <Col span={6}>
                      <ProFormDigit
                        name="startTime"
                        label="开始时间(第几个小时开始)"
                        rules={[{ required: true, message: '请输入开始时间' }]}
                      />
                    </Col>
                    <Col span={6}>
                      <ProFormDigit
                        name="endTime"
                        label="结束时间(至第几个小时)"
                        rules={[{ required: true, message: '请输入结束时间 ' }]}
                      />
                    </Col>
                    <Col span={6}>
                      <ProFormSelect
                        name="priceUnit"
                        label="时间类型"
                        rules={[{ required: true, message: '请输入时间类型' }]}
                        options={[
                          { value: 60, label: '一小时制' },
                          { value: 30, label: '半小时制' },
                        ]}
                      />
                    </Col>
                    <Col span={5}>
                      <ProFormDigit
                          name="pricing"
                          label="价格"
                          fieldProps={ {
                            addonAfter: '￥',
                            precision: 2
                          } }
                          rules={ [ { required: true, message: '请输入价格' } ] }
                      />
                    </Col>
                  </Row>
                )}
              </ProFormList>
            </Panel>
          </Collapse>
        </ProCard>
      </ProForm>
    </Spin>
  );
};
